package arrays;

public class Array05 {
    public static void main(String[] args) {
        int[] nums = {2,2,1};
        System.out.println(majorityElement(nums));
        System.out.println(majorityElement(new int[]{4,1,2,1,2}));
        System.out.println(majorityElement(new int[]{1}));

    }

    //给定一个大小为 n 的数组，找到其中的多数元素。
    //多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
    public static int majorityElement(int[] nums) {
        int count = 0;
        int candidate = 0;

        for (int num : nums) {
            if (count == 0) {
                candidate = num;
            }
            count += (num == candidate) ? 1 : -1;
        }
        return candidate;
    }
}
